package org.spring.boot.sample.hystrix.command;

import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.exception.HystrixBadRequestException;
import com.netflix.hystrix.exception.HystrixTimeoutException;

/**
 * 
 * 以下四种情况将触发getFallback调用：
 * 1）run()方法抛出非HystrixBadRequestException异常
 * 2）run()方法调用超时
 * 3）熔断器开启拦截调用
 * 4）线程池/队列/信号量是否跑满
 * 
 * 实现getFallback()后，执行命令时遇到以上4种情况将被fallback接管，不会抛出异常或其他
 */
public class HystrixCommandException extends HystrixCommand<String>{

	private String name;
	
	public HystrixCommandException(String name){
		super(HystrixCommandGroupKey.Factory.asKey("ExceptionGroup"));
		this.name = name;
	}

	@Override
	protected String run() throws Exception {
		/** 会触发fallback的case */
		/*int j = 0;
		while(true){
			j ++;
			System.out.println("run() " + j);
		}*/
		
		/*int i = 10 / 0;
		return name;*/
		//throw new HystrixTimeoutException();
		//throw new RuntimeException("throw RuntimeException");
		//throw new Exception("throw exception");
		
		/** 不会触发fallback的case */
		/*try {
			// 被捕获的异常不会触发fallback
			throw new Exception("try catch exception");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return name;*/
		// HystrixBadRequestException异常由非法参数或非系统错误引起，不会触发fallback，也不会被计入熔断器
		throw new HystrixBadRequestException("HystrixBadRequestException is never trigger fallback");
	}

	@Override
	protected String getFallback() {
		return "fallback " + name;
	}
	
	
}
